import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class Manager extends User {
    private static SimpleDateFormat sdf=new SimpleDateFormat("yyy_MM_dd HH:mm");
    private List<Ticket>tickets=new ArrayList<>();
    private List<Movie> showingMovies = new ArrayList<>();
    private List<Screening> screenings = new ArrayList<>();
    private List<Movie>movies=new ArrayList<>();
    private List<String> logOperations = new ArrayList<>();
    public List<Movie> searchMovies(String keyword) {
        List<Movie> result = new ArrayList<>();
        for (Movie movie : movies) {
            if (movie.getTitle().contains(keyword) || movie.getDirector().contains(keyword) || movie.getActors().contains(keyword)) {
                result.add(movie);
            }
        }
        return result;
    }
    public Ticket querySaleData(String scope) {//查询销售数据
        Screening screening = null;
        List<Seat> seats = new ArrayList<>();
        double totalPrice = 0.0;
        Date date = new Date();
        int totalTickets = 0;
        double totalAmount = 0.0;
        int refundTickets = 0;
        double refundAmount = 0.0;
        List<Screening> screenings = listScreeningsByScope(scope);
        for (Screening s : screenings) {
            totalTickets += s.getSoldTicketsCount();
            totalAmount += s.getTotalSales();
            for (Ticket t : tickets) {
                if (t.getScreening().equals(s)) {
                    seats.addAll(t.getSeats());
                    totalPrice += t.getTotalPrice();
                    if (t.isRefunded()) {
                        refundTickets++;
                        refundAmount += t.getTotalPrice();
                    }
                }
            }
        }
        List<Ticket> allTickets =new ArrayList<>();
        for (Ticket t : allTickets) {
            if (t.getScreening().getScreeningId().equals(scope)) {
                totalTickets += t.getTotalTickets();
                totalAmount += t.getTotalPrice();
            }
        }
        Ticket stats = new Ticket(UUID.randomUUID().toString(), screening, seats, totalPrice, date, totalTickets, totalAmount, refundTickets, refundAmount);
        stats.setTotalTickets(totalTickets);
        stats.setTotalAmount(totalAmount);
        return stats;
    }
    public List<Screening> getScreenings() {//获得有效排期
        List<Screening> valid = new ArrayList<>();
        for (Screening s : screenings) {
            if (!s.hasSoldTickets()) {
                valid.add(s);
                System.out.println("当前存储的场次数量："+screenings.size());
            }
        }
        return valid;
    }
    public List<Movie> getShowingMovies() {//获取正在上映影片信息
        List<Movie> showingMovies = new ArrayList<>();
        for (Movie movie : movies) {
            if (isMovieShowing(movie)) {
                showingMovies.add(movie);
            }
        }
        return showingMovies;
    }
    private boolean isMovieShowing(Movie movie) {//判断影片是否正在上映
        for (Screening screening : screenings) {
            if (screening.getMovie().equals(movie) && screening.getHasSoldTicket()) {
                return true;
            }
        }
        return false;
    }
    public Screening findScreeningById(String screeningId) {//按Id查找排期
        for (Screening s : screenings) {
            if (s.getScreeningId().equals(screeningId)) {
                return s;
            }
        }
        return null;
    }
    public void autoArrangeScreenings() {//自动排期操作
        System.out.println("Manager " + getUsername() + " is auto arranging screenings.");
    }
    public void deleteScreening(Screening screening) {//删除排期，记录日志
        Log log = new Log("LOG-" + System.currentTimeMillis(), new Date(), "DELETE_SCREENING", this.getUsername());
        log.recordLog("Deleted screening: " + screening.getScreeningId());
    }
    public List<Screening> listScreeningsByScope(String scope) {//按时间范围筛选排期
        List<Screening> allScreenings = this.screenings;
        List<Screening> filteredScreenings = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (Screening screening : allScreenings) {
            Date date=screening.getTime();
            LocalDateTime screeningTime =date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            if ("today".equals(scope)) {
                if (screeningTime.toLocalDate().equals(now.toLocalDate())) {
                    filteredScreenings.add(screening);
                }
            } else if ("3days".equals(scope)) {
                if (!screeningTime.isAfter(now.plusDays(3))) {
                    filteredScreenings.add(screening);
                }
            } else if ("week".equals(scope)) {
                if (!screeningTime.isAfter(now.plusWeeks(1))) {
                    filteredScreenings.add(screening);
                }
            }
        }
        return filteredScreenings;
    }
    public Ticket querySalesData(String scope) {
        String someString = "";
        Screening screening = null;
        List<Seat> seats = new ArrayList<>();
        double totalPrice = 0.0;
        Date date = new Date();
        int totalTickets = 0;
        double totalAmount= 0.0;
        int refundTickets= 0;
        double refundAmount= 0.0;
        if ("当日".equals(scope)) {

        } else if ("当周".equals(scope)) {

        } else if ("当月".equals(scope)) {

        }
        return new Ticket(someString, screening, seats, totalPrice, date, totalTickets, totalAmount, refundTickets, refundAmount);
    }
    public List<Screening> listScreenings(String scope) {
        List<Screening> result = new ArrayList<>();
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (Screening s : screenings) {
            Date screeningTime = s.getTime();
            String screeningDateStr = sdf.format(screeningTime);
            if ("最近一周".equals(scope)) {
                if (daysBetween(screeningTime, now) <= 7) {
                    result.add(s);
                }
            } else if ("当日".equals(scope)) {
                String todayDateStr = sdf.format(new Date());
                if (screeningDateStr.equals(todayDateStr)) {
                    result.add(s);
                }
            } else if ("近3日".equals(scope)) {
                if (daysBetween(screeningTime, now) <= 3) {
                    result.add(s);
                }
            }
        }
        return result;
    }
    public void logOperation(String operation, String details) {
        String logEntry = "时间: " + sdf.format(new Date()) + ", 操作: " + operation + ", 详情: " + details;logOperations.add(logEntry);
        System.out.println("日志记录成功：" + logEntry);
    }
    private int daysBetween(Date startDate, Date endDate) {
        long diffInMillis = endDate.getTime() - startDate.getTime();
        return (int) (diffInMillis / (24 * 60 * 60 * 1000));
    }
    public Movie findMovieById(String movieId) {
        for (Movie movie : movies) {
            if (movie.getMovieId().equals(movieId)) {
                return movie;
            }
        }
        return null;
    }
    public List<Movie> listAllMovies() {
        return new ArrayList<>(movies);
    }
    public List<Movie>getMovies(){
        return this.movies;
    }
    public boolean hasScreening(Movie movie) {
        for (Screening screening : screenings) {
            if (screening.getMovie().equals(movie)) {
                return true;
            }
        }
        return false;
    }
    public void removeTicket(Ticket ticket) {
        tickets.remove(ticket);
    }
    public Manager(String userId, String username, String password, Date registerTime, String phone) {
        super(userId, username, password, registerTime, UserType.MANAGER, phone);
    }
    public void addMovie(Movie movie) {
        if (movie != null && !movies.contains(movie)) {
            movies.add(movie);
            System.out.println(" 已添加电影: " + movie.getTitle());
        }
        showingMovies.add(movie);
        Log log = new Log("LOG-" + System.currentTimeMillis(), new Date(), "ADD_MOVIE", this.getUsername());
        log.recordLog("Added movie: " + movie.getTitle());
    }
    public void modifyMovieInfo(Movie movie) {
        Log log = new Log("LOG-" + System.currentTimeMillis(), new Date(), "MODIFY_MOVIE_INFO", this.getUsername());
        log.recordLog("Modified info for movie: " + movie.getTitle());
    }
    public void deleteMovie(Movie movie) {
        showingMovies.remove(movie);
        Log log = new Log("LOG-" + System.currentTimeMillis(), new Date(), "DELETE_MOVIE", this.getUsername());
        log.recordLog("Deleted movie: " + movie.getTitle());
    }
    public void addScreening(Screening screening) {
        Log log = new Log("LOG-" + System.currentTimeMillis(), new Date(), "ADD_SCREENING", this.getUsername());
        log.recordLog("已添加场次: " + screening.getMovie().getTitle());
        System.out.println("addScreening 被调用，尝试添加场次：" + screening.getScreeningId());
        screenings.add(screening);
        System.out.println("当前 screenings 数量：" + screenings.size());
        screenings.add(screening);
    }
    public void modifyScreening(Screening screening) {//修改排期
        screening.setInfo(screening.getCinemaHall(), screening.getTime(), screening.getPrice());
        Log log = new Log("LOG-" + System.currentTimeMillis(), new Date(), "MODIFY_SCREENING", this.getUsername());
        log.recordLog("Modified screening: " + screening.getScreeningId());
    }
    public List<Screening> listAllScreenings() {
        return new ArrayList<>();
    }
    public boolean deleteMovie(String movield) {
        Movie movie = findMovieById(movield);
        if (movie != null) {
            movies.remove(movie);
            System.out.println("电影《" + movie.getTitle() + "》已删除。");
            return true;
        } else {
            System.out.println("未找到ID为 " + movield + " 的电影。");
            return false;
        }
    }
    public boolean updateMovie(String movield, Movie newMovie) {//更新影片信息
        Movie oldMovie = findMovieById(movield);
        if (oldMovie != null) {
            int index = movies.indexOf(oldMovie);
            movies.set(index, newMovie);
            System.out.println("电影《" + oldMovie.getTitle() + "》已更新为《" + newMovie.getTitle() + "》。");
            return true;
        } else {
            System.out.println("未找到ID为 " + movield + " 的电影，无法修改。");
            return false;
        }
    }
    public void viewDailySales() {
        System.out.println("Manager " + getUsername() + " is viewing daily sales.");
    }
    public void viewWeeklySales() {
        System.out.println("Manager " + getUsername() + " is viewing weekly sales.");
    }
    public void viewMonthlySales() {
        System.out.println("Manager " + getUsername() + " is viewing monthly sales.");
    }
    @Override
    public void login() {
        System.out.println("Manager " + getUsername() + " logged in.");
    }
    @Override
    public void logout() {
        System.out.println("Manager " + getUsername() + " logged out.");
    }
    @Override
    public void managePassword() {
        System.out.println("Manager " + getUsername() + " is managing password.");
    }
}
